﻿/*
* Sunbox DataView
* Tool for customizing layout in SharePoint
*
* Examples and documentation at: http://sunbox.codeplex.com
* 
* Copyright (c) 2011 - 2012 SKB KONTUR
* Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
* 
* Version: 1.5.3 (27/02/2012)
* Requires: jQuery v1.3+ (for options), Fancybox 1.3.4 (for options), CodeMirror (for options)
*
* LGPL license:
*   http://www.gnu.org/licenses/lgpl.html
*/

$.fn.extend({
    datasourceeditorpart: function (options) {
        var aObj = [];
        $(this).each(function () {
            if (!$(this).hasClass("dve-done")) {
                aObj.push(new DataSourceEditorPart(this, options));
                $(this).addClass("dve-done");
            }
        });
        if (aObj.length == 1)
            return aObj[0];
        return aObj;
    }
});

DataSourceEditorPart = (function () {
    var $dsEditorSingle;

    function DataSourceEditorPart(container, options) {
        $dsEditorSingle = this;
        this.options = $.extend({}, this.defaults(), options);
        this.jqContainer = $(container);
        this.init();
    }

    DataSourceEditorPart.prototype.init = function () {

        this.jqHidden = $("#" + this.options.controlid);
        if (this.jqHidden.val().length > 0)
            this.datasources = JSON.parse(this.jqHidden.val());
        else
            this.datasources = [];

        this.jqContainer.append("<div class='ds-wrap'></div>");

        //init lang
        if (typeof SunboxDataView.lang[this.options.lang] != 'undefined')
            this.locale = SunboxDataView.lang[this.options.lang];
        else
            this.locale = SunboxDataView.lang.en;

        this.resfreshDataSourceList();


        $(".ds-form-getlists").live("click", function () {
            var opt = $dsEditorSingle.getCurrentFormValues(this);

            SPData.getSPListCollection(function (lists) {
                opt.viewSelect.html("<option selected='selected' value=''>" + $dsEditorSingle.locale.dataSourceEditorListItemNotSelected + "</option>");
                var selectedList = opt.listSelect.attr("data-value");

                var html = "<option " + (selectedList.length == 0 ? "selected='selected'" : "") + " value=''>" + $dsEditorSingle.locale.dataSourceEditorListItemNotSelected + "</option>";

                for (var i = 0; i < lists.length; i++) {
                    if (typeof (lists[i].Hidden) == 'undefined' || lists[i].Hidden.toString().toLowerCase() != "true")
                        html += "<option " + (selectedList == lists[i].ID ? "selected='selected'" : "") + " value='" + lists[i].ID + "'>" + lists[i].Title + "</option>";
                }
                opt.listSelect.html(html);
                opt.listSelect.change();

            }, function () {
            }, opt.weburl);
        });

        $(".ds-form-lists").live("change", function () {
            var opt = $dsEditorSingle.getCurrentFormValues(this);
            if (opt.listid.length == 0) return;

            var selectedView = opt.viewSelect.attr("data-value");

            SPData.getSPViewCollection(opt.listid, function (views) {
                var html = "<option " + (selectedView.length == 0 ? "selected='selected'" : "") + " value=''>" + $dsEditorSingle.locale.dataSourceEditorListItemNotSelected + "</option>";
                for (var i = 0; i < views.length; i++) {
                    if (typeof (views[i].Hidden) == 'undefined' || views[i].Hidden.toString().toLowerCase() != "true")
                        html += "<option " + (selectedView == views[i].Name ? "selected='selected'" : "") + " value='" + views[i].Name + "'>" + views[i].DisplayName + "</option>";
                }
                opt.viewSelect.html(html);

            }, function () {
            }, opt.weburl);

        });
        //Добавление источника
        $(".ds-list-add").live("click", function () {
            var newsource = {};
            newsource.Id = $dsEditorSingle.generateGuid();
            newsource.ListId = "";
            newsource.ViewId = "";
            newsource.Query = "";
            newsource.ViewFields = "";
            newsource.RowLimit = 0;
            newsource.Title = "";
            newsource.WebUrl = "";
            newsource.PagerStyle = 0;
            newsource.DynamicContentContainerId = "";
            newsource.PagerContainerId = "";
            newsource.PagerDisplayName = "";
            newsource.CacheOnClient = true;

            $dsEditorSingle.datasources.push(newsource);
            $dsEditorSingle.resfreshDataSourceList();
        });
        //Сохранение настроек источника
        $(".ds-form-submit").live("click", function () {
            if (!$dsEditorSingle.validateForm(this))
                return;
            var opt = $dsEditorSingle.getCurrentFormValues(this);
            var source = $dsEditorSingle.getSourceById(opt.id);
            if (source == null) return;
            source.Title = opt.titleInput.val().length > 0 ? opt.titleInput.val() : $dsEditorSingle.formatSourceTitle(opt.listSelect.find("option:selected").text());
            source.WebUrl = opt.webInput.val();
            source.ListId = opt.listid;
            source.ViewId = opt.viewid;
            source.RowLimit = opt.rowInput.val();
            source.Query = opt.queryEditor.getValue();
            source.ViewFields = opt.viewfieldsEditor.getValue();
            source.PagerStyle = parseInt(opt.pagerStyleInput.val());
            source.DynamicContentContainerId = opt.dynamicContentContainerId.val();
            source.PagerContainerId = opt.pagerContainerId.val();
            source.PagerDisplayName = opt.pagerDisplayName.val();
            source.RecursiveScope = opt.recursiveCheck.is(":checked");
            source.CacheOnClient = opt.cacheCheck.is(":checked");

            $.fancybox.close();

            $dsEditorSingle.resfreshDataSourceList();
            $dsEditorSingle.saveDataSources();

        });
        //Переключение вкладок
        $(".snbx-tab").live("click", $dsEditorSingle.tabClicked);
        //Отмена настроек источника
        $(".ds-form-cancel").live("click", function () {
            $.fancybox.close();
        });
        //Удаление источника
        $(".ds-list-remove").live("click", function () {
            if (!confirm($dsEditorSingle.locale.dataSourceEditorDeleteConfirm))
                return;
            var k = -1;
            for (var i = 0; i < $dsEditorSingle.datasources.length; i++) {
                if ($dsEditorSingle.datasources[i].Id == $(this).attr("data-id")) {
                    k = i;
                    break;
                }
            }
            if (k > 0) {
                $dsEditorSingle.datasources.splice(k, 1);
                $dsEditorSingle.resfreshDataSourceList();
                $dsEditorSingle.saveDataSources();
            }

        });
    };

    DataSourceEditorPart.prototype.validateForm = function (obj) {
        var opt = $dsEditorSingle.getCurrentFormValues(obj);
        opt.form.find(".ds-form-error").remove();
        if (opt.listid != null && opt.listid.length == 0) {
            opt.listSelect.after(" <span class='ds-form-error ds-required'>" + this.locale.dataSourceEditorListValidationMessage + "</span>");
            return false;
        }
        opt.form.find(".ds-form-error").remove();
        return true;
    };

    DataSourceEditorPart.prototype.resetForm = function (obj) {
        var opt = $dsEditorSingle.getCurrentFormValues(obj);
        var source = $dsEditorSingle.getSourceById(opt.id);
        if (source == null) return;
        opt.queryEditor.setValue(source.Query);
        opt.queryEditor.refresh();
        opt.rowInput.val(source.RowLimit);
        opt.listSelect.val(source.ListId);
        opt.viewSelect.val(source.ViewId);
        opt.webInput.val(source.WebUrl);
        opt.viewfieldsEditor.setValue(source.ViewFields);

        opt.pagerStyleInput.val(source.PagerStyle.toString());
        opt.dynamicContentContainerId.val(source.DynamicContentContainerId);
        opt.pagerContainerId.val(source.PagerContainerId);
        opt.pagerDisplayName.val(source.PagerDisplayName);

        if (source.RecursiveScope)
            opt.recursiveCheck.attr("checked", "checked");
        else
            opt.recursiveCheck.removeAttr("checked");

        if (source.CacheOnClient)
            opt.cacheCheck.attr("checked", "checked");
        else
            opt.cacheCheck.removeAttr("checked");

        opt.form.find(".ds-form-error").remove();
    };

    DataSourceEditorPart.prototype.getCurrentFormValues = function (obj) {
        var $form = $(obj).closest(".ds-form");
        var $sourceId = $form.find(".ds-form-id");
        var $titleInput = $form.find(".ds-form-title");
        var $listsSelect = $form.find(".ds-form-lists");
        var $viewSelect = $form.find(".ds-form-view");
        var $weburlInput = $form.find(".ds-form-weburl");
        var $rowInput = $form.find(".ds-form-rowlimit");
        var $queryEditor = window["queryeditor" + $form.attr("data-id")];
        var $viewFieldsEditor = window["viewfieldseditor" + $form.attr("data-id")];
        ;
        var $pagerDisplayNameInput = $form.find(".ds-form-pagerdisplayname");
        var $pagerStyleInput = $form.find(".ds-form-pagingstyle");
        var $dynamiccontentcontaineridInput = $form.find(".ds-form-dynamiccontentcontainerid");
        var $pagercontaineridInput = $form.find(".ds-form-pagercontainerid");

        var $recursiveCheck = $form.find(".ds-form-recursive");
        var $cacheCheck = $form.find(".ds-form-cacheonclient");
        var $webUrl = ($weburlInput.val().length > 0 ? $weburlInput.val() : undefined);

        return { id: $sourceId.val(), form: $form, listid: $listsSelect.val(), listSelect: $listsSelect, viewid: $viewSelect.val(), viewSelect: $viewSelect, weburl: $webUrl, webInput: $weburlInput, rowInput: $rowInput, queryEditor: $queryEditor, viewfieldsEditor: $viewFieldsEditor, titleInput: $titleInput, pagerStyleInput: $pagerStyleInput, pagerDisplayName: $pagerDisplayNameInput, dynamicContentContainerId: $dynamiccontentcontaineridInput, pagerContainerId: $pagercontaineridInput, recursiveCheck: $recursiveCheck, cacheCheck: $cacheCheck };
    };

    DataSourceEditorPart.prototype.resfreshDataSourceList = function () {
        var $this = this;
        var wrap = this.jqContainer.find(".ds-wrap");
        wrap.html(this.buildDataSourceList(this.datasources));
        $(".ds-list-settings").fancybox({
            onComplete: function () {
                var form = $(this.orig[0]).attr("href");
                $(form).find(".ds-form-getlists").click(); //get lists automatically
                var sourceId = $(form).attr("data-id");
                window["queryeditor" + sourceId].refresh();
                window["viewfieldseditor" + sourceId].refresh();
            },
            onClosed: function () {
                var form = $(this.orig[0]).attr("href");
                $this.resetForm($(form).find(".ds-form-getlists"));
            },
            titleShow: false,
            width: 831,
            autoDimensions: false,
            height: "auto",
            autoSize: false,
            transitionIn: "none",
            transitionOut: "none",
            openSpeed: 0,
            closeSpeed: 0
        });
    };

    DataSourceEditorPart.prototype.saveDataSources = function () {
        var sourcedata = JSON.stringify($dsEditorSingle.datasources);
        $dsEditorSingle.jqHidden.val(sourcedata);
    };

    DataSourceEditorPart.prototype.buildDataSourceList = function (dataSources) {
        var html = "<div class='ds-list-wrap'>";
        for (var i = 0; i < dataSources.length; i++) {
            dataSources[i].Id = dataSources[i].Id.replace(/\-/g, "");
            html += "<div class='ds-list-item'>";
            html += (i + 1) + ". " + (dataSources[i].Title.length > 0 ? dataSources[i].Title : this.locale.dataSourceEditorNotConfigured) + " (<a id='ds-list-settings-" + dataSources[i].Id + "' class='ds-list-settings' href='#ds-lightbox-" + dataSources[i].Id + "'>" + this.locale.dataSourceEditorEdit + "</a> | <a href='javascript:void(0);' data-id='" + dataSources[i].Id + "' class='ds-list-remove'>" + this.locale.dataSourceEditorDelete + "</a>)";
            html += "<div style='display:none;'>" + this.buildDataSourceForm(dataSources[i]) + "</div>";
            html += "</div>";
        }
        html += "<div class='ds-list-buttons'>";
        html += "<a class='ds-list-add' href='javascript:void(0);'>" + this.locale.dataSourceEditorAdd + "</a>";
        html += "</div>";
        html += "</div>";
        return html;
    };

    DataSourceEditorPart.prototype.getSourceById = function (id) {
        for (var i = 0; i < $dsEditorSingle.datasources.length; i++) {
            if ($dsEditorSingle.datasources[i].Id == id)
                return $dsEditorSingle.datasources[i];
        }
        return null;
    };

    DataSourceEditorPart.prototype.buildDataSourceForm = function (datasource) {

        var html = "<div class='ds-form' data-id='" + datasource.Id + "' id='ds-lightbox-" + datasource.Id + "'>";
        //tabs:
        html += "<div class='snbx-tabs-container'>";
        html += "   <div rel='.sourcetab-" + datasource.Id + "' class='snbx-tab snbx-activetab'>";
        html += "       <span>" + this.locale.dataSourceEditorSourceTabTitle + "</span>";
        html += "   </div>";
        html += "   <div rel='.pagertab-" + datasource.Id + "' class='snbx-tab'>";
        html += "       <span>" + this.locale.dataSourceEditorPageTabTitle + "</span>";
        html += "   </div>";
        html += "   <div rel='.additionaltab-" + datasource.Id + "' class='snbx-tab'>";
        html += "       <span>" + this.locale.dataSourceEditorAdvancedTabTitle + "</span>";
        html += "   </div>";
        html += "</div>";

        //source:
        html += "<div class='sourcetab-" + datasource.Id + " snbx-tab-content snbx-activetabcontent' >";

        html += "<input type='hidden' class='ds-form-id' value='" + datasource.Id + "' />";

        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label'>" + this.locale.dataSourceEditorSourceName + ":</div>";
        html += "   <div class='ds-form-field'><input class='ds-form-title' data-sourceid='" + datasource.Id + "' id='ds-form-title-" + datasource.Id + "' value='" + datasource.Title + "' type='text' /></div>";
        html += "</div>";

        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label'>" + this.locale.dataSourceEditorWebUrl + ":</div>";
        html += "   <div class='ds-form-field'><input class='ds-form-weburl' data-sourceid='" + datasource.Id + "' id='ds-form-siteurl-" + datasource.Id + "' value='" + datasource.WebUrl + "' type='text' /><input type='button' data-sourceid='" + datasource.Id + "' class='ds-form-getlists' value='" + this.locale.dataSourceEditorGetListsButtonText + "' /></div>";
        html += "</div>";

        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label'>" + this.locale.dataSourceEditorList + "<span class='ds-required'>*</span>:</div>";
        html += "   <div class='ds-form-field'><select class='ds-form-lists' data-value='" + datasource.ListId + "' data-sourceid='" + datasource.Id + "' id='ds-form-listid-" + datasource.Id + "'></select></div>";
        html += "</div>";

        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label'>" + this.locale.dataSourceEditorView + ":</div>";
        html += "   <div class='ds-form-field'><select class='ds-form-view' data-value='" + datasource.ViewId + "' data-sourceid='" + datasource.Id + "' id='ds-form-viewid-" + datasource.Id + "'></select></div>";
        html += "</div>";

        html += "<div class='ds-form-line ds-form-queryline'>";
        html += "   <div class='ds-form-label'>" + this.locale.dataSourceEditorQuery + ":</div>";
        html += "   <div class='ds-form-field' style='font-size:16px;'><textarea rows='15' class='ds-form-query' cols='85' data-sourceid='" + datasource.Id + "' id='ds-form-query-" + datasource.Id + "'>" + datasource.Query + "</textarea></div>";
        html += "</div>";

        html += "<div class='ds-form-line ds-form-viewfields'>";
        html += "   <div class='ds-form-label'>" + this.locale.dataSourceEditorVuewFields + ":</div>";
        html += "   <div class='ds-form-field' style='font-size:16px;'><textarea rows='10' class='ds-form-viewfields' cols='85' data-sourceid='" + datasource.Id + "' id='ds-form-viewfields-" + datasource.Id + "'>" + datasource.ViewFields + "</textarea></div>";
        html += "</div>";

        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label'>" + this.locale.dataSourceEditorRowLimit + ":</div>";
        html += "   <div class='ds-form-field'><input value='" + datasource.RowLimit + "' data-sourceid='" + datasource.Id + "' class='ds-form-rowlimit' id='ds-form-siteurl-" + datasource.Id + "' type='text' /></div>";
        html += "</div>";
        html += "</div>";
        //pager tab:
        html += "<div class='pagertab-" + datasource.Id + " snbx-tab-content' style='display:none;'>";
        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label large-width'>" + this.locale.dataSourceEditorPagerTypeLabel + ":</div>";
        html += "   <div class='ds-form-field'>";
        html += "       <select class='ds-form-pagingstyle'>";
        html += "           <option value='0' " + (datasource.PagerStyle == 0 ? "selected='selected'" : "") + ">" + this.locale.dataSourceEditorPagerTypeNone + "</option>";
        html += "           <option value='1' " + (datasource.PagerStyle == 1 ? "selected='selected'" : "") + ">" + this.locale.dataSourceEditorPagerTypeReplacement + "</option>";
        html += "           <option value='2' " + (datasource.PagerStyle == 2 ? "selected='selected'" : "") + ">" + this.locale.dataSourceEditorPagerTypeAdding + "</option>";
        html += "           <option value='3' " + (datasource.PagerStyle == 3 ? "selected='selected'" : "") + ">" + this.locale.dataSourceEditorPagerTypeAuto + "</option>";
        html += "       </select>";
        html += "   </div>";
        html += "</div>";
        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label large-width' title='" + this.locale.dataSourceEditorPagerDinamicContainerIdDescription + "'>" + this.locale.dataSourceEditorPagerDinamicContainerId + ":</div>";
        html += "   <div class='ds-form-field' ><input value='" + datasource.DynamicContentContainerId + "' data-sourceid='" + datasource.Id + "' class='ds-form-dynamiccontentcontainerid' type='text' /></div>";
        html += "</div>";
        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label large-width' title='" + this.locale.dataSourceEditorPagerContainerIdDescription + "'>" + this.locale.dataSourceEditorPagerContainerId + ":</div>";
        html += "   <div class='ds-form-field' ><input value='" + datasource.PagerContainerId + "' data-sourceid='" + datasource.Id + "' class='ds-form-pagercontainerid' type='text' /></div>";
        html += "</div>";
        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label large-width' title='" + this.locale.dataSourceEditorPagerLinkTitleDescription + "'>" + this.locale.dataSourceEditorPagerLinkTitle + ":</div>";
        html += "   <div class='ds-form-field' ><input value='" + datasource.PagerDisplayName + "' data-sourceid='" + datasource.Id + "' class='ds-form-pagerdisplayname' type='text' /></div>";
        html += "</div>";
        html += "</div>";
        //additional options
        html += "<div class='additionaltab-" + datasource.Id + " snbx-tab-content' style='display:none;'>";
        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label large-width'>" + this.locale.dataSourceEditorRecursiveScope + ":</div>";
        html += "   <div class='ds-form-field'>";
        html += "       <input " + (datasource.RecursiveScope ? "checked='checked'" : "") + " class='ds-form-recursive' type='checkbox' />";
        html += "   </div>";
        html += "</div>";
        html += "<div class='ds-form-line'>";
        html += "   <div class='ds-form-label large-width'>" + this.locale.dataSourceEditorCacheOnClient + ":</div>";
        html += "   <div class='ds-form-field'>";
        html += "       <input " + (datasource.CacheOnClient ? "checked='checked'" : "") + " class='ds-form-cacheonclient' type='checkbox' />";
        html += "   </div>";
        html += "</div>";
        html += "</div>";
        html += "<div class='ds-form-buttons' >";
        html += "   <input type='button' class='ds-form-submit' value='" + this.locale.dataSourceEditorSubmit + "' />  <a class='ds-form-cancel' href='javascript:void(0);'>" + this.locale.dataSourceEditorCancel + "</a>";
        html += "</div>";

        //codemirror:

        html += "<script>";
        html += "var queryeditor" + datasource.Id + " = CodeMirror.fromTextArea(document.getElementById('ds-form-query-" + datasource.Id + "'), { mode: {name: 'xml', alignCDATA: true}, lineNumbers: true });";
        html += "var viewfieldseditor" + datasource.Id + " = CodeMirror.fromTextArea(document.getElementById('ds-form-viewfields-" + datasource.Id + "'),  { mode: {name: 'xml', alignCDATA: true}, lineNumbers: true });";
        html += "</script>";

        html += "</div>";
        return html;
    };

    DataSourceEditorPart.prototype.defaults = function () {
        return {
            controlid: "",
            lang: 'en'
        };
    };
    /*================ TABS ==================*/
    DataSourceEditorPart.prototype.tabClicked = function () {
        if ($(this).is(".snbx-activetab")) return;
        var selector = $(this).attr("rel");
        var tab = $(selector);
        if (tab.length == 0) return;
        $(this).closest(".ds-form").find(".snbx-activetabcontent").hide().removeClass("snbx-activetabcontent");
        tab.show().addClass("snbx-activetabcontent");

        $(this).closest(".ds-form").find(".snbx-activetab").removeClass("snbx-activetab");
        $(this).addClass("snbx-activetab");
    };

    /*================ HELPERS ==================*/
    DataSourceEditorPart.prototype.formatSourceTitle = function (title) {
        var newTitle = title.toString().replace(" ", "_");
        return newTitle;
    };

    DataSourceEditorPart.prototype.s4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };

    DataSourceEditorPart.prototype.generateGuid = function () {
        return ($dsEditorSingle.s4() + $dsEditorSingle.s4() + $dsEditorSingle.s4() + $dsEditorSingle.s4() + $dsEditorSingle.s4() + $dsEditorSingle.s4() + $dsEditorSingle.s4() + $dsEditorSingle.s4());
    };

    return DataSourceEditorPart;
})();